package com.atswust.shake.interceptor;

import com.atswust.shake.config.ResponBean;
import com.atswust.shake.utils.JWTutils;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @author liushuai
 * @create 2022-02-06 11:52
 */

public class JWTInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头中令牌
         String token = request.getHeader("token");
         ResponBean resb = new ResponBean();
        try {
            //验证令牌
         JWTutils.verify(token);
            //放行请求
         return true;
        } catch (SignatureVerificationException e) {
            e.printStackTrace();
             resb = ResponBean.error("无效签名",401);
        }catch (TokenExpiredException e){
            e.printStackTrace();
             resb = ResponBean.error("token过期",401);

        }catch (AlgorithmMismatchException e){
            e.printStackTrace();
             resb = ResponBean.error("加密算法不一致", 401);
        }catch (Exception e){
            e.printStackTrace();
             resb = ResponBean.error("token无效", 401);
        }
        //将map 专为json  jackson
        String json = new ObjectMapper().writeValueAsString(resb);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);
        return false;
    }
}
